package com.film.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.film.service.user.FetchUserInfoService;
import com.film.utils.MySqlConnection;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class FetchUserInfoServiceImpl implements FetchUserInfoService {
    @Override
    public JSONObject gerUserInfo(String username) throws SQLException {
        JSONObject resp = new JSONObject();

        //拉取用户名和头像信息
        String sql = "select * from User where username = " + "'" + username + "'";
        Statement stmt = MySqlConnection.connect.createStatement();
        System.out.println(sql);
        ResultSet resultSet = stmt.executeQuery(sql);
        if (!resultSet.isBeforeFirst()) { //resultSet为空
            resp.put("error_message", "用户名错误");
            return resp;
        }
        String userId = "";
        if (resultSet.next()) {
            JSONObject user = new JSONObject();
            String name = resultSet.getString("username");
            String photoUrl = resultSet.getString("photo_url");
            userId = resultSet.getString("id");
            user.put("username", name);
            user.put("photoUrl", photoUrl);
            resp.put("user", user);
        }


        // 拉取该用户喜欢的电影
        // 多表查询
        sql = "select * from Movie where id in (select movie_id from User_Favor_Movie where user_id = "+ userId + ")";
        System.out.println(sql);
        stmt = MySqlConnection.connect.createStatement();
        resultSet = stmt.executeQuery(sql);
        LinkedList<JSONObject> favorMovies = new LinkedList<>();
        while (resultSet.next()) {
            JSONObject item = new JSONObject();
            String name = resultSet.getString("name");
            String imgUrl = resultSet.getString("image");
            Integer stars = resultSet.getInt("stars");
            HashMap<String, String> inf = new HashMap<>();
            item.put("name", name);
            item.put("imgUrl", imgUrl);
            item.put("stars", String.valueOf(stars));
            favorMovies.add(item);
        }

        resp.put("movies", favorMovies);
        resultSet.close();
        stmt.close();
        return resp;
    }
}
